package com.sleep.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sleep.common.Utils;
import com.sleep.model.UserDeviceInfoEntity;
import com.sleep.model.UserInfoEntity;
import com.sleep.service.IUserDeviceService;
import com.sleep.service.IUserService;
import com.sun.xml.internal.ws.api.ha.StickyFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DateTimeException;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.DataFormatException;

/**
 * Created by fadinglan on 2017/4/10.
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    @Qualifier("userServiceImpl")
    private IUserService userService;

    @Autowired
    @Qualifier("userDeviceServiceImpl")
    private IUserDeviceService userDeviceService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)

    public @ResponseBody Map<String, Object> userLogin(@RequestBody JSONObject response){

        String account = response.get("account").toString();
        String password = response.get("password").toString();

        Map<String, Object> result = new HashMap<>();

        List<UserInfoEntity> accountList = userService.checkAccount(account);

        if (accountList == null || accountList.isEmpty()) {

            result.put("flag", 0);
            result.put("cause", "账号不存在");

        } else {

            List<UserInfoEntity> passwordList = userService.checkPassword(password);

            if (passwordList == null || passwordList.isEmpty()) {

                result.put("flag", 2);
                result.put("cause", "密码错误");

            } else {

                result.put("flag", 1);

            }
        }

        return result;
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public @ResponseBody Map<String, Object> userRegister(@RequestBody JSONObject request){

        Map<String, Object> result = new HashMap<>();

        String cellphone = request.get("account").toString();
        String password = request.get("password").toString();

        List<UserInfoEntity> userList = userService.checkAccount(cellphone);

        if (userList == null || userList.isEmpty()) {

            UserInfoEntity user = new UserInfoEntity();

            user.setVcCellphone(cellphone);
            user.setVcPassword(password);

            userService.save(user);

            result.put("flag", 1);

        } else {

            result.put("flag", 2);
            result.put("cause", "用户已存在");

        }

        return result;

    }

    @RequestMapping(value = "/get/base_info", method = RequestMethod.GET)
    public @ResponseBody Map<String, Object> getUserInfo(@RequestParam(value = "account") String account){

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = new HashMap<>();

        List<UserInfoEntity> accountList = userService.getUserInfo(account);

        if (accountList == null || accountList.isEmpty()) {

            result.put("flag", 0);
            result.put("cause", "用户不存在");

        } else {

            UserInfoEntity userInfo = accountList.get(0);

            if (Utils.isNull(userInfo.getVcUserName())) {
                params.put("name", "乐享智家");
            } else {
                params.put("name", userInfo.getVcUserName());
            }

            if (Utils.isNull(userInfo.gettUserBirthday())) {
                params.put("birthday", new Date());
            } else {
                params.put("birthday", userInfo.gettUserBirthday());
            }

            if (Utils.isNull(userInfo.getTiUserSex())) {
                params.put("sex", 1);
            } else {
                params.put("sex", userInfo.getTiUserSex());
            }

            Object[] paramsArr = {params};

            result.put("flag", 1);
            result.put("params", paramsArr);
        }

        return result;
    }

    @RequestMapping(value = "/update/base_info", method = RequestMethod.POST)
    public @ResponseBody Map<String, Object> updateUserInfo(@RequestParam(value = "account") String account, @RequestBody JSONObject request){

        Map<String, Object> result = new HashMap<>();

        List<UserInfoEntity> accountList = userService.getUserInfo(account);

        UserInfoEntity userInfo = new UserInfoEntity();

        if (accountList == null || account.isEmpty()) {
            result.put("flag", 0);
            result.put("cause", "用户不存在");
            return result;
        } else {

            userInfo = accountList.get(0);

            if (request.containsKey("name")) {
                userInfo.setVcUserName(request.getString("name"));
            }

            if (request.containsKey("sex")) {

                Byte sex = request.getByte("sex");

                if (sex == 0 || sex == 1) {
                    userInfo.setTiUserSex(sex);
                } else {
                    result.put("flag", 0);
                    result.put("cause", "性别取值超出范围");
                    return result;
                }

            }

            if (request.containsKey("birthday")) {
                String birthString = request.getString("birthday");
                String pattern = "yyyy-MM-dd";
                SimpleDateFormat df = new SimpleDateFormat(pattern);
                Date birthday = new Date();
                try {
                    birthday = df.parse(birthString);
                    userInfo.settUserBirthday(birthday);
                } catch (ParseException e) {
                    result.put("flag", 0);
                    result.put("cause", "生日取值超出范围");
                    return result;
                }

            }

            userService.update(userInfo);

            result.put("flag", 1);

        }

        return result;
    }

    @RequestMapping(value = "/device/bind", method = {RequestMethod.POST})
    @ResponseBody
    Map<String, Object> deviceBind(@RequestBody String params){

        Map<String, Object> result = new HashMap<>();
        int flag = 0;

        JSONObject json = (JSONObject) JSON.parse(params);

        String userId = json.get("userId").toString();
        String deviceId = json.get("deviceId").toString();

        List<UserDeviceInfoEntity> userDeviceList = userDeviceService.queryDevice(userId);

        if (userDeviceList == null || userDeviceList.isEmpty()) {
            UserDeviceInfoEntity userDeviceInfoEntity = new UserDeviceInfoEntity();

            userDeviceInfoEntity.setiUserId(userId);
            userDeviceInfoEntity.setVcDeviceId(deviceId);

            userDeviceService.save(userDeviceInfoEntity);

            flag = 1; //绑定成功

        } else if (userDeviceList != null && !userDeviceList.isEmpty()) {

            flag = 2; //已绑定
        }

        result.put("flag", flag);
        return result;
    }

}
